<?php

/**
 * @copyright 2011
 * @version $Id$
 * @access public
 * @author oriotiori

 */

class Admin_Model_Categories extends Zend_Db_Table_Abstract{

    protected $_name = 'categories';
    
    /**
     * Obtiene categorias
     * @param Array $to
     * @return array $data
     */
    public function getCategories($id=0)
    {
    	$TO = new Admin_Model_TO_Categories();
    	$data=array();

    	try{
    		$sql=$this->getAdapter()->select()
    					->from(array('c' => TABLE_PREFIX.$this->_name), "*")
    					->joinLeft(array('i' => TABLE_PREFIX.'images'), "i.Id=c.Id_Image", array('Thumb'))
    					->where("c.Id_Parent=?", $id);
    
    		$res = $this->getAdapter()->fetchAll($sql);
    		$rowCount=count($res);
    			
    		if($rowCount>0)
    		{
    			foreach($res as $dt){
    				$TO->setId($dt['Id']);
    				$TO->setType('Category');
    				$TO->setThumb($dt['Thumb']);
    				$TO->setName($dt['Category']);
    				$TO->setDescription($dt['Description']);
    				$TO->setStatus($dt['Status']);
    				
    				$TO->add();
    			}
    			$data = $TO->getAllData();
    			return $data;
    		}
    	}catch(Exception $e)
    	{
    		$error=array($e->getFile(), 'Exception: '.$e->getMessage());
    		$ExceptionHandler= new Default_Model_ExceptionHandler();
    		$ExceptionHandler->saveErrors($error);
    	}
    	return false;
    }
    
    
    
    /**
     * Obtiene categorias by id
     * @param int $id
     * @return array $data
     */
    public function readCategoryById($id=0)
    {
    	$TO = new Admin_Model_TO_Categories();
    	$data=array();
    	try{
    		$sql=$this->getAdapter()->select()
    		    		->from(array('c' => TABLE_PREFIX.$this->_name), "*")
    					->joinLeft(array('i' => TABLE_PREFIX.'images'), "i.Id=c.Id_Image", array('Thumb'));
    		;
    		$sql = $sql->where("c.Id=?", $id);    
    
    		$res = $this->getAdapter()->fetchAll($sql);
    		$rowCount=count($res);
    			
    		if($rowCount>0)
    		{
    			foreach($res as $dt){
    				$TO->setId($dt['Id']);
    				$TO->setType('Category');
    				$TO->setThumb($dt['Thumb']);
    				$TO->setName($dt['Category']);
    				$TO->setIdParent($dt['Id_Parent']);
    				$TO->setIdImage($dt['Id_Image']);
    				$TO->setDescription($dt['Description']);
    				$TO->setStatus($dt['Status']);
    			}
    			$data = $TO->getAllVars();
    			return $data;
    		}
    	}catch(Exception $e)
    	{
    		$error=array($e->getFile(), 'Exception: '.$e->getMessage());
    		$ExceptionHandler= new Default_Model_ExceptionHandler();
    		$ExceptionHandler->saveErrors($error);
    	}
    	return false;
    }
    
    
    /**
     * Agrega nueva categoria
     * @param Array $to
     * @return int
     */
    public function addCategory($to)
    {
        try{
            $data = array(
                  	'Category'     => $to['Name'],
                  	'Description'  => (!empty($to['Description'])) ? $to['Description'] :new Zend_Db_Expr('null'),
                  	'Id_Image'  	=> 0,
                  	'Id_Parent'  	=> (int)$to['IdParent']
            );

            $res = $this->getAdapter()->insert(TABLE_PREFIX.$this->_name ,$data);
            $lastId= $this->getAdapter()->lastInsertId();

            return $lastId;

        }catch(Exception $e)
        {
            $error=array($e->getFile(), 'Exception: '.$e->getMessage());
            $ExceptionHandler= new Default_Model_ExceptionHandler();
            $ExceptionHandler->saveErrors($error);
        }
        return false;
    }

    
    /**
     * @param Array $to
    * @return boolean
    */
    public function updateCategory($to)
    {
    	try{
	    	$data = array(
			    'Category'     => $to['Name'],
			    'Description'  => (!empty($to['Description'])) ? $to['Description'] :new Zend_Db_Expr('null')
        	);
    
	    	$where[]="Id=".$to['Id'];
		    $res = $this->getAdapter()->update(TABLE_PREFIX.$this->_name ,$data, $where);    
	    }catch(Exception $e)
	    {
		    $error=array($e->getFile(), 'Exception: '.$e->getMessage());
		    $ExceptionHandler= new Default_Model_ExceptionHandler();
		    $ExceptionHandler->saveErrors($error);
        }
    	return false;
    }
    
    /**
    * @param Array $to
     * @return boolean
    */
    public function AddImageDB($to)
    {
	    try{
		    $data = array(
			    'Id_Image'  => (int)$to['IdPicture']
		    );
		    $where[]="Id=".$to['IdCategory'];
		    $res = $this->getAdapter()->update(TABLE_PREFIX.$this->_name ,$data, $where);
		    return $res;
	    	
	    }catch(Exception $e)
	    {
		    $error=array($e->getFile(), 'Exception: '.$e->getMessage());
		    $ExceptionHandler= new Default_Model_ExceptionHandler();
		    $ExceptionHandler->saveErrors($error);
	    }
	    return false;
    }
    
    
    /**
    * Obtiene arbolde categorias
     * @param int $id
    * @return array $data
    */
    public function getTreeCatById($id, &$data=array())
    {
	    $TO = new Admin_Model_TO_Categories();

	    try{
		    $sql=$this->getAdapter()->select()->from(TABLE_PREFIX.$this->_name, "*");
		    $sql = $sql->where("Id=?", $id);
	    	
		    $res = $this->getAdapter()->fetchAll($sql);
	        $rowCount=count($res);
	     	
		    if($rowCount>0)
		    {
		    	foreach($res as $dt){
		    		$data[]=$dt;
		    		if($dt['Id_Parent']>0){
		    			$this->getTreeCatById($dt['Id_Parent'], $data);
		    		}
			    }
	    	}
	    	return array_reverse($data);	    	
	    }catch(Exception $e)
	    {
		    $error=array($e->getFile(), 'Exception: '.$e->getMessage());
		    $ExceptionHandler= new Default_Model_ExceptionHandler();
		    $ExceptionHandler->saveErrors($error);
	    }
	    return false;
    }
      
    
    
    /**
     * Obtiene arbolde categorias hijos
     * @param int $id
     * @return array $data
     */
    public function getChildsCatById($id, &$data=array())
    {
    	$TO = new Admin_Model_TO_Categories();

    	try{
    		$sql=$this->getAdapter()->select()->from(TABLE_PREFIX.$this->_name, "*");
    		$sql = $sql->where("Id_Parent=?", $id);

    		$res = $this->getAdapter()->fetchAll($sql);
    		$rowCount=count($res);
    		 
    		if($rowCount>0)
    		{
    			foreach($res as $dt){
    				$data[]=$dt;
    			}
    		}
    		return $data;
    	}catch(Exception $e)
    	{
    		$error=array($e->getFile(), 'Exception: '.$e->getMessage());
    		$ExceptionHandler= new Default_Model_ExceptionHandler();
    		$ExceptionHandler->saveErrors($error);
    	}
    	return false;
    }


    /**
     * Obtiene arbolde categorias hijos recursivo
     * @param int $id
     * @return array $data
     */
    public function getChildsRecursiveCatById($id, &$data=array())
    {
    	$TO = new Admin_Model_TO_Categories();
		
    	$recursive=$this->getChildsCatById($id);

    	if($recursive){
	    	foreach($recursive as $rc){
	    		$data[]=$rc;
	    		$this->getChildsRecursiveCatById($rc['Id'], $data);
	    	}
    	}
    	return $data;
    }


    
    
    
/**
 * Borramos categorias y subcategorias y productos dentro de estas.
 * @param int id
 * @return boolean
 */
    public function deleteCategoryById($id=0)
    {
        try{
            $facadeImage= new Admin_Model_Facade_ImageHandler();
            $facadeProduct= new Admin_Model_Facade_Products();
            $dataCat=$this->readCategoryById($id);
            
            $tree=$this->getChildsRecursiveCatById($id);
            
            foreach($tree as $child){
            	$productos=$facadeProduct->getProductsByCategory($child['Id']);
            	if($productos){
	            	foreach($productos as $pr){
	            		$facadeProduct->deleteProductById($pr['Id']);
	            		$facadeProduct->deleteProductFeaturedById($pr['Id']);
	            	}
            	}
            	$res = $this->getAdapter()->delete(TABLE_PREFIX.$this->_name ,"Id=".$child['Id']);
            }
            $productos=$facadeProduct->getProductsByCategory($id);
            if($productos){
	            foreach($productos as $pr){
	            	$facadeProduct->deleteProductById($pr['Id']);
	            	$facadeProduct->deleteProductFeaturedById($pr['Id']);
	            }
            }
            
            $res = $this->getAdapter()->delete(TABLE_PREFIX.$this->_name ,"Id=".$id);
            $facadeImage->deleteImage($to['IdImage']);
            
            return $res;
        }catch(Exception $e)
        {
            $error=array($e->getFile(), 'Exception: '.$e->getMessage());
            $ExceptionHandler= new Default_Model_ExceptionHandler();
            $ExceptionHandler->saveErrors($error);
        }
        return false;
    }

    
    
    /**
    * Crea Thumb
     * @param Array $to
    * @return boolean
    */
    public function CreateThumb($to)
    {
	    try{
	    	$imageHandler= new Admin_Model_ImageHandler();
	    	$imageHandler->CreateThumb($to);
	    	return true;
	    }catch(Exception $e)
    	{
    		$error=array($e->getFile(), 'Exception: '.$e->getMessage());
    		$ExceptionHandler= new Default_Model_ExceptionHandler();
            $ExceptionHandler->saveErrors($error);
    	}
    	return false;
   }
    


}
